export type TypedKey<T> = {
  key: string;
  defaultValue: T;
  // 添加类型标记，用于运行时类型检查
  __type?: T;
};

export interface Share {
  [key: string]: unknown;
}

export type Middleware<T = unknown> = (
  key: string,
  value: T,
  next: (value: T) => void,
) => void;

// 增强createTypedKey函数，添加更严格的类型检查
export function createTypedKey<T>(key: string, defaultValue: T): TypedKey<T> {
  if (typeof key !== 'string' || key.trim() === '') {
    throw new Error('Key must be a non-empty string');
  }
  return { key, defaultValue };
}

// 完善isTypedKey类型守卫，添加更精确的类型检查
export function isTypedKey<T>(key: unknown): key is TypedKey<T> {
  return (
    key !== null &&
    typeof key === 'object' &&
    'key' in key &&
    'defaultValue' in key &&
    typeof (key as TypedKey<T>).key === 'string'
  );
}

// 增强类型守卫，添加类型参数推断
export function assertTypedKey<T>(
  key: unknown,
  typeGuard?: (value: unknown) => value is T,
): asserts key is TypedKey<T> {
  if (!isTypedKey(key)) {
    throw new Error('Value must be a TypedKey');
  }
  if (typeGuard && !typeGuard((key as TypedKey<T>).defaultValue)) {
    throw new Error('TypedKey defaultValue does not match expected type');
  }
}

// 添加中间件类型守卫
export function isMiddleware<T>(value: unknown): value is Middleware<T> {
  return typeof value === 'function';
}

// 添加Share类型守卫
export function isShare(value: unknown): value is Share {
  return value !== null && typeof value === 'object';
}

// 添加类型辅助函数，用于提取TypedKey的值类型
export type ExtractTypedKeyType<K> = K extends TypedKey<infer T> ? T : never;
